package edu.cuit.campus.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/19 11:09
 */
@Controller
@RequestMapping("/files")
public class FileUploadController {

    @ResponseBody
    @RequestMapping("/upload")
    public String upload(@RequestParam(name = "username") String username,
                         @RequestParam(name = "avatar") MultipartFile avatar) throws IOException {
        if(avatar != null && avatar.getSize() > 0){
            System.out.println("content type:" + avatar.getContentType());
            System.out.println("file name:" + avatar.getOriginalFilename());
            System.out.println("file size:" + avatar.getSize());

            var file = new File("D:/cuit/files/images", avatar.getOriginalFilename());

            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            //上传文件至服务器
            avatar.transferTo(file);
            return "http://img.cuit.com/images/" + avatar.getOriginalFilename();
        }

        return "请选择要上传的文件";
    }
}
